package leetcode;

public class MyAtoi {
    public static void main(String[] args) {
        int i = myAtoi("  0000000000012345678");
        System.out.println(i);

    }
//        Pattern.matches()正则匹配方法
    //字符串转整数
    public static int myAtoi(String s) {
        long n = 0;
        int flag = 1;
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                index++;
            } else if (s.charAt(i) == '-') {
                index++;
                flag = -1;
                break;
            } else if (s.charAt(i) == '+') {
                index++;
                break;
            } else if (48 <= s.charAt(index) && s.charAt(index) < 58) {
                break;
            } else {
                return 0;
            }
        }
        if (s.length() <= index) return 0;
        if (!(48 <= s.charAt(index) && s.charAt(index) < 58)) {
            return 0;
        }
        for (int i = index; i < s.length(); i++) {
            if (48 <= s.charAt(i) && s.charAt(i) < 58) {
                char c = s.charAt(i);
                n = n * 10 + ((int) c - 48);
                if (n > Integer.MAX_VALUE) break;
            } else {
                break;
            }
        }
        int limit = Integer.MAX_VALUE;
        if (flag == -1) {
            limit = Integer.MIN_VALUE;
        }
        return (int) n * flag == n * flag ? (int) n * flag : limit;
    }
}
